<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>阅读</title>
    <script src="/common/lib/jquery-3.6.0.js"></script>
    <script src="/common/lib/vue.js"></script>
    <link rel="stylesheet" href="/common/style.css">
    <script src="/common/common.js"></script>
    <style>
        .read{
            width: 100%;
            height: 100%;
        }
        .twotitle{

        }
        .primarytitle{
            font-size: 20px;
            line-height: 23px;
        }
        .secondtitle{
            font-size: 12px;
            line-height: 14px;
        }
        .lrbtn{
            width: 40px;
            height: 100%;
            line-height: 100%;
            position: absolute;
            top: 0px;
            font-family: monospace;
            font-weight: bolder;
            border: none;
            background-color: rgba(255, 255, 255, 0.021);
            font-size: 40px;
            color: lightgray;
            transition-duration: 300ms;
        }
        .lrbtn:hover{
            transition-duration: 300ms;
            color: black;
            background-color: rgba(255, 255, 255, 0.623);
        }
    </style>
</head>
<body>

    <div class="head">
        <button class="menubtn" style="background-image: url('/common/img/slider_handle.png');background-size: contain" onclick="toggledrawer()"></button>
        <div class="title twotitle">
            <p class="title primarytitle" id="title1">&nbsp;</p>
            <p class="title secondtitle" id="title2">&nbsp;</p>
        </div>
        <div class="flexspace"></div>

        <button id="btnbookmark" class="menubtn bookmarkoff" onclick="toggleBookmark()"></button>
        <button class="menubtn" style="background-image: url('/common/img/menu.png');" onclick="togglemenu()"></button>
    </div>
    <div class="container">
        <div class="read">
            <div class="progressbar"></div>
            <iframe src="" class="mainframe" width="100%" height="100%" frameborder="0" id="bookframe"></iframe>
            <button class="lrbtn" style="left: 0px;" onclick="prev()">&lt;</button>
            <button class="lrbtn" style="right:0px;" onclick="next()">&gt;</button>
        </div>

        <div id="optionmenumain" class="optionmenu" style="display: none" class="optionmenu">
            <div id="optionmenubg" style="background-color: rgba(255,255,255,0.01)" class="drawerbg fadeout" onclick="togglemenu()"></div>
            <div id="optionmenufg" class="optionmenufg fadeout menuhide">
                <div class="optionmenuitem darkhover typemnu0" style="background-image: url('/common/img/ic_menu_textsize.png')" onclick="mnuFontsize()">字体大小</div>
                <div class="optionmenuitem darkhover typemnu0" style="background-image: url('/common/img/ic_menu_save.png')" onclick="togglemenu();mnuQS()">快速存档</div>
                <div class="optionmenuitem darkhover typemnu0" style="background-image: url('/common/img/ic_menu_load.png')" onclick="togglemenu();mnuQL()">快速读档</div>
                <div class="optionmenuitem darkhover typemnu1" style="background-image: url('/common/img/ic_menu_textsize.png')" onclick="togglemenu();setFontSize(15)">100%</div>
                <div class="optionmenuitem darkhover typemnu1" style="background-image: url('/common/img/ic_menu_textsize.png')" onclick="togglemenu();setFontSize(19)">125%</div>
                <div class="optionmenuitem darkhover typemnu1" style="background-image: url('/common/img/ic_menu_textsize.png')" onclick="togglemenu();setFontSize(22.5)">150%</div>
                <div class="optionmenuitem darkhover typemnu1" style="background-image: url('/common/img/ic_menu_textsize.png')" onclick="togglemenu();setFontSize(26)">175%</div>
                <div class="optionmenuitem darkhover typemnu1" style="background-image: url('/common/img/ic_menu_textsize.png')" onclick="togglemenu();setFontSize(30)">200%</div>
                <div class="optionmenuitem darkhover typemnu0" style="background-image: url('/common/img/ic_menu_home.png')" onclick="home()">返回主页</div>
            </div>
        </div>

        <div id="drawermain" style="display: none;" class="drawerslider">
            <div id="drawerbg" class="drawerbg fadeout" onclick="toggledrawer()"></div>
            <div id="drawerfg" class="drawerfg drawerhide">
                <div class="tabcontainer">
                    <div class="tabheaders">
                        <div class="tabheader darkhover tabselected tab1" onclick="switchtab(this,'tabpage1')">目录</div>
                        <div class="tabheader darkhover tab2" onclick="switchtab(this,'tabpage2')">存档</div>
                    </div>
                    <div class="tabpages" id="leftvue">
                        <div class="tabpage" id="tabpage1">
                            <div id="tocs" class="auto-scroll">
                                <div class="tableofcontent" v-for="chapter in chapters" >
                                    <img v-bind:width="chapter.stack * 10"/>{{chapter.label.trim()}}<img src="/common/img/ic_list_go.png" width="40" height="40" class="darkhover btngo" v-on:click="chapterClick(chapter)"/>
                                </div>
                            </div>
                        </div>
                        <div class="tabpage" style="display: none" id="tabpage2">
                            <div id="saves" class="auto-scroll">
                                <div class="savecard" v-for="save in saves">
                                    <p class="savetime" v-if="save.saveTime>0">{{getSaveInfo(save)}}&nbsp;</p>
                                    <div class="line" style="position: absolute;top: 24px;width: 100%"></div>
                                    <div class="savedesc">
                                        <p class="savetitle">{{save.name}}</p>
                                        <div class="savebtns">
                                            <div class="savebtn darkhover" v-on:click="saveClick(save)">保存</div>
                                            <div class="savebtn darkhover" v-on:click="loadClick(save)">读取</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="snackbar"></div>
<!--    UI Effect-->
    <script>
        var draweropen = false;
        function toggledrawer(){
            if(!draweropen){
                $("#drawermain").show();
                $("#drawerbg").removeClass("fadeout");
                $("#drawerfg").removeClass("drawerhide");
            }
            else{
                $("#drawerbg").addClass("fadeout");
                $("#drawerfg").addClass("drawerhide");
                setTimeout(()=>{
                    $("#drawermain").hide();
                },300);
            }
            draweropen=!draweropen;
        }
        function closeproc(ev){
            alert(1);
            ev.preventDefault();
        }
        var menuopen = false;
        function togglemenu(){
            if(!menuopen){
                $("#optionmenumain").show();
                $("#optionmenubg").removeClass("fadeout");
                $("#optionmenufg").removeClass("menuhide").removeClass("fadeout");
                $("#optionmenufg>.typemnu0").show();
                $("#optionmenufg>.typemnu1").hide();
            }
            else{
                $("#optionmenubg").addClass("fadeout");
                $("#optionmenufg").addClass("menuhide").addClass("fadeout");
                setTimeout(()=>{
                    $("#optionmenumain").hide();
                },220);
            }
            menuopen=!menuopen;
        }

        function switchtab(tab1,tab){
            $(".tabheaders>.tabheader").removeClass("tabselected");
            $(tab1).addClass("tabselected");
            $(".tabpages>*").hide();
            $("#"+tab).show();
        }



        function dateFormat(fmt, date) {
            let ret;
            const opt = {
                "y+": date.getFullYear().toString(),        // 年
                "M+": (date.getMonth() + 1).toString(),     // 月
                "d+": date.getDate().toString(),            // 日
                "H+": date.getHours().toString(),           // 时
                "m+": date.getMinutes().toString(),         // 分
                "s+": date.getSeconds().toString()          // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
            };
            for (let k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                    fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
                };
            };
            return fmt;
        }


    </script>

<!--    EPUB Interop-->
    <script>

        var subdoc = null;
        $(function (){
            initInteract();
            loadAllBookmark();
            subdoc = document.getElementById("bookframe").contentWindow;
            subdoc.location.replace("static/index.html");
        });
        var messageInteract = {};

        var fontsize = parseInt(localStorage.getItem("fontsize"));
        if(!isFinite(fontsize)){fontsize=15;}
        if(isNaN(fontsize)){fontsize=15;}

        function setFontSize(fs){
            fontsize=fs;
            localStorage.setItem("fontsize",fs);
            subdoc.setTextSize(fs);
        }

        function initInteract(){
            messageInteract["EPUB_BOOK_INIT_START"]=function (arg){
                $.ajax({url:"api/bmload/0",success:function (result) {
                        var bookmark = JSON.parse(result);
                        subdoc.loadBookAtUrl("",bookmark.epubcft,fontsize)
                    }});
                $.ajax({url:"api/bookname",success:function (result) {
                        $("#title1").text(result);
                        document.title=result;
                    }});
            };
            messageInteract["EPUB_BOOK_INIT_SUCCESS"]=function (arg){
                subdoc.reportBookInfo();
            };
            messageInteract["EPUBTOC"]=function (arg){
                var tocs1 = JSON.parse(arg);
                var toc2=[];
                var stack=0;
                var tocproc=function (target,parent) {
                    parent.stack = stack;
                    target.push(parent);
                    var subtoc = parent.subitems;

                    for (let i = 0; i < subtoc.length; i++) {
                        stack++;
                        tocproc(target,subtoc[i]);
                        stack--;
                    }
                }
                for (let i = 0; i < tocs1.length; i++) {
                    tocproc(toc2,tocs1[i]);
                }
                leftvue.chapters=toc2;
            };
            messageInteract["EPUBSPINE"]=function (arg){

            };
            messageInteract["REPORT_LOCATION"]=function (arg){
                locationPage = arg;
                showReadingProgress();
            };
            messageInteract["REPORT_CHAPTER"]=function (arg){
                if(arg!=null && arg!=""){
                    locationChapter = arg;
                    showReadingProgress();
                }
            };
            messageInteract["SHOW_PROGRESS"]=function (arg){
                if(arg=="1"){
                    $(".progressbar").show();
                }
                else{
                    $(".progressbar").hide();
                }
            };
            messageInteract["AUTO_SAVE_REQUIRE"]=function (arg){
                currentPositoin = arg;
                autoSaveCountdown=-1;
                if(autoSaver==null){
                    autoSaver = setInterval(autoSaveFunc,100);
                }
            };
            messageInteract["GET_SAVING"]=function (arg){
                currentPositoin = arg;
                autoSaveCountdown=30;
                if(autoSaver==null){
                    autoSaver = setInterval(autoSaveFunc,100);
                }
            };
        }
        var locationChapter="";
        var locationPage="1/1";
        var currentPositoin = "";
        function showReadingProgress(){
            $("#title2").text("["+locationPage+"] "+locationChapter);
        }
        function reportMessage(type,content){
            //console.warn("<"+type+"::"+content);
            messageInteract[type](content);
        }
        function mnuFontsize(){
            $("#optionmenufg>.typemnu1").show();
            $("#optionmenufg>.typemnu0").hide();
        }
        function mnuQS(){
            toast("正在存档");
            $.ajax("api/bmsave/"+1+"?name="+encodeURI(locationPage+"\n"+locationChapter)+"&cfi="+encodeURI(currentPositoin),{
                success:function () {
                    loadAllBookmark();
                    toast("存档已保存");
                },error:function () {
                    toast("存档失败")
                }});
        }
        function mnuQL(){
            toast("正在读档");
            $.ajax({url:"api/bmload/1",success:function (result) {
                    var bookmark = JSON.parse(result);
                    subdoc.navTo(bookmark.epubcft);
                    toast("存档已读取");
                },error:function () {
                    toast("读取失败")
                }});
        }

        var lockedBookmark = false;
        var lockedBookmarkCfi="";
        function toggleBookmark(){
            if(!lockedBookmark){
                lockedBookmark=true;
                lockedBookmarkCfi = currentPositoin;
                $("#btnbookmark").removeClass("bookmarkoff");
                $("#btnbookmark").addClass("bookmarkon");
            }
            else{
                lockedBookmark=false;
                subdoc.navTo(lockedBookmarkCfi);
                $("#btnbookmark").addClass("bookmarkoff");
                $("#btnbookmark").removeClass("bookmarkon");
            }
        }

        var leftvue = new Vue({
           el:"#leftvue",
           data:{
               chapters:[],
               saves:[]
           },
            methods:{
                chapterClick:function (chapter) {
                    toggledrawer();
                    subdoc.navTo(chapter.href);
                },
                saveClick:function (save) {
                    toast("正在存档");
                    $.ajax("api/bmsave/"+save.slot+"?name="+encodeURI(locationPage+"\n"+locationChapter)+"&cfi="+encodeURI(currentPositoin),{
                        success:function () {
                            loadAllBookmark();
                            toast("存档已保存");
                        },error:function () {
                            toast("存档失败")
                        }});
                },
                loadClick:function (save) {
                    subdoc.navTo(save.epubcft);
                    toggledrawer();
                    toast("存档已读取");
                },
                getSaveInfo:function (save) {
                    if(save.saveTime==-1){return "";}
                    var type="存档 #"+(save.slot-1);
                    if(save.slot==0){type="自动存档";}
                    if(save.slot==1){type="快速存档";}
                    var date = new Date();
                    date.setTime(save.saveTime);
                    return type+" "+dateFormat("yyyy-MM-dd HH:mm:ss",date);
                }
            }
        });
        function loadAllBookmark(){
            $.ajax({url:"api/bmloadall",success:function (result) {
                    leftvue.saves = JSON.parse(result);
                },error:function () {
                    toast("获取存档失败")
                }})
        }

        var autoSaveCountdown = 30;
        var autoSaver = null;
        var autoSaveFunc = function (){
            if(autoSaveCountdown > 0){
                autoSaveCountdown--;
            }
            else{
                $.ajax("api/bmsave/"+0+"?name="+encodeURI(locationPage+"\n"+locationChapter)+"&cfi="+encodeURI(currentPositoin),{
                    success:function () {
                        loadAllBookmark();
                    },error:function () {
                        toast("自动存档失败")
                    }});
                clearInterval(autoSaver);
                autoSaver=null;
            }
        }

        function toast(str){
            $(".snackbar").text(str).removeClass("snackbar-anim");
            setTimeout(function (){$(".snackbar").addClass("snackbar-anim")},40);
        }
        function home(){
            $.ajax("api/bmsave/"+0+"?name="+encodeURI(locationPage+"\n"+locationChapter)+"&cfi="+encodeURI(currentPositoin),{
                    success:function () {
                        window.location.href = "api/close";
                    },error:function () {
                        window.location.href = "api/close";
                    }});
        }

        document.addEventListener("keyup",function(e){
            console.log(e);
            eval(keyToDirection(e));
        });
        
        function prev(){subdoc.window.prev();}
        function next(){subdoc.window.next();}

    </script>
</body>
</html>